import 'package:znmm/UI/ProductPages/model/product_model.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/graphql_service.dart';
import 'package:znmm/network/notify_listener.dart';
import 'package:graphql/client.dart';

import '../model/category_model.dart';
import 'category_qlstr.dart';

class CategoryMag {
  static final CategoryMag _instance = CategoryMag._internal();

  factory CategoryMag() {
    return _instance;
  }

  CategoryMag._internal();

  void clearn() {}

  void doSomething() {
    print("Doing something...");
  }

  String categorySlug = "";
  String firstSlug = ""; //第一个slug

  //------------------category---------------
  late final List<CategoryModel> _categoryList = [];
  List<CategoryModel> getCategoryList() => _categoryList;

  void reqProductCategorieGraql() {
    if (_categoryList.isEmpty) {
      GraphQLService.performQuery(
        GET_PRODUCT_CATEGORIES_PARENT,
        HttpLink(APIUrl.graphqlUrl),
        variables: {
          'parent': 0, // 传递parent参数的值
          'first': 10, // 传递first参数的值
          //'after': 'your-cursor-value', // 传递after参数的值
        },
        // bIsShowLoading: true,
        // bShowResponse: true,
        (data) {
          if (data == null) return;
          // On success
          print('Query successful: $data');
          if (data['productCategories'] == null) return;

          var nodesList = data['productCategories']['nodes'] as List;
          print("nodesList:${nodesList.length}");
          _categoryList.clear();
          for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
            var fJson = nodesList[iIndex];

            CategoryModel pmodel = CategoryModel();
            pmodel.databaseId = MyGlobal.checkNullOrZero(fJson['databaseId']);
            pmodel.name = MyGlobal.checkNullOrEmpty(fJson["name"]);
            pmodel.slug = MyGlobal.checkNullOrEmpty(fJson["slug"]);
            pmodel.bIsTitle = true;
            _categoryList.add(pmodel);
            if (iIndex == 1) {
              firstSlug = pmodel.slug;
              CategoryMag().reqProductByCateSlugGraql(pmodel.slug); //请求默认第一个
            }
            //将二级菜单合并到这里
            var scendList = fJson["children"]['nodes'] as List;
            for (int iCount = 0; iCount < scendList.length; iCount++) {
              var sJson = scendList[iCount];
              pmodel = CategoryModel();
              pmodel.databaseId = MyGlobal.checkNullOrZero(sJson['databaseId']);
              pmodel.name = MyGlobal.checkNullOrEmpty(sJson['name']);
              pmodel.slug = MyGlobal.checkNullOrEmpty(sJson['slug']);
              _categoryList.add(pmodel);
            }
          }
          print("_categoryList:${_categoryList.length}");
        },
      );
    } else {
      reqProductByCateSlugGraql(firstSlug);
    }
  }

//------------------产品---------------
  late final List<ProductModel> _categProducList = [];
  List<ProductModel> getCategProducList() => _categProducList;

  void reqProductByCateSlugGraql(String slugStr) {
    print("slugStr:$slugStr");
    if (slugStr.isEmpty) {
      slugStr = categorySlug;
    }
    categorySlug = slugStr;

    GraphQLService.performQuery(
      GET_PRODUCTS_BY_CATEGORY_SLUG,
      HttpLink(APIUrl.graphqlUrl),
      variables: {
        'first': 100,
        'categorySlug': categorySlug, //hotel-fragrance  aroma-diffuser
      },
      bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        if (data == null) return;
        // On success
        //print('Query successful: $data');
        if (data['products'] == null) return;

        var nodesList = data['products']['edges'] as List;
        print("nodesList:${nodesList.length}");
        _categProducList.clear();
        for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
          var jsonVar = nodesList[iIndex]["node"];

          ProductModel pmodel = ProductModel();
          pmodel.name = MyGlobal.checkNullOrEmpty(jsonVar["name"]);
          pmodel.slug = MyGlobal.checkNullOrEmpty(jsonVar["slug"]);
          pmodel.sourceUrl =
              MyGlobal.checkNullOrEmpty(jsonVar["image"]["sourceUrl"]);
          pmodel.price = MyGlobal.checkNullOrEmpty(jsonVar["price"]);
          int iAverage = MyGlobal.checkNullOrZero(jsonVar['averageRating']);
          pmodel.averageRating = iAverage.toDouble();
          pmodel.stockStatus =
              MyGlobal.checkNullOrEmpty(jsonVar["stockStatus"]);
          ;

          _categProducList.add(pmodel);
        }
        print("_categProducList:${_categProducList.length}");

        NotifyCenter().postNotification(NotifyKey.categProductKey);
      },
    );
  }

  //------------------产品详情 要传slug---------------
  void reqProductBySlugGraql(String strSlug,
      {void Function(ProductModel)? callback}) {
    if (strSlug.isEmpty) {
      MyGlobal.showInfo("slug null!");
      return;
    }
    //cotton-candy-triangle-puff-2
    //cnus-x3art-luxury-waterless-diffuser-with-custom-logo-perfume-for-car-and-home-2

    GraphQLService.performQuery(
      PRODUCTBYSLUG_QUERY,
      HttpLink(APIUrl.graphqlUrl),
      variables: {
        'slug': strSlug,
      },
      bIsShowLoading: true,
      //bShowResponse: true,
      (data) {
        print('Query successful: $data');

        if (data == null) return;
        // On success
        if (data['products'] == null) return;
        ProductModel pmodel = ProductModel.fromJson2(data);
        if (callback != null) {
          callback(pmodel);
        }
      },
    );
  }
}
